<template>
  <a-modal
    v-model:visible="show"
    :title="t('aiot.serviceOrder.competeWorkOrder')"
    width="600px"
    height="600px"
    class="dispatchContainer"
    :confirm-loading="confirmLoading"
    @ok="ok"
  >
    <div ref="content" class="max-full">
      <DynamicForm ref="completeIns" :model="model" :model-form-setting="modelFormSetting" :force-flex-row="false" />
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import { nextTick, ref, watch } from "vue";
import type { DynamicFormExpose, FormItemData } from "/@/components/CURDDialog/models";
import { FormAddItem } from "/@/api/aiot/message/models";
import { saveCompleteds } from "/@/api/aiot/serviceWorkOrder";
import { message } from "ant-design-vue";
import { CompleteWorkOrder } from "/@/api/aiot/serviceWorkOrder/models";
import { useOrderModal } from "./useOrderModal";

const { t } = useI18n();
const props = defineProps<{
  workOrderId?: string;
  visible: boolean;
}>();
const emits = defineEmits(["create", "update:visible"]);
const completeIns = ref<DynamicFormExpose>();
const show = ref<boolean>(false);
const { completeModel: model, completeModelFormSetting: modelFormSetting } = useOrderModal();
watch(
  () => props.visible,
  (v) => {
    show.value = v;
    if (!v) {
      reset();
    }
  }
);
let firstShow = true;
watch(show, (v) => {
  emits("update:visible", v);
  if (v) {
    nextTick(() => {
      completeIns.value?.initFormItemComponentData();
    });
  }
  if (firstShow) {
    firstShow = false;
  }
});
//
function reset() {
  if (completeIns.value) {
    completeIns.value.resetFields();
    model.value.completedAppendix = [];
    model.value.completionSituation = "";
  }
}
const content = ref<HTMLDivElement>();
const confirmLoading = ref<boolean>(false);
function ok() {
  if (!completeIns.value) return;
  completeIns.value
    .validate()
    .then(async (data: FormAddItem) => {
      let obj: CompleteWorkOrder = { workOrderId: props.workOrderId || "" };
      Object.assign(obj, model.value);
      confirmLoading.value = true;
      let req = (await saveCompleteds(obj)) || null;
      confirmLoading.value = false;
      if (req) {
        emits("update:visible", false);
        message.success(t("common.operSuccess"));
        emits("create");
      }
    })
    .catch(() => {
      if (content.value) {
        (content.value.parentNode as HTMLDivElement).scrollTop = 0;
      }
    });
}
</script>
